package com.funtonow.jqdk.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.app.ActivityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.adapter.HotRecommedAdapter;
import com.funtonow.jqdk.base.BaseActivity;
import com.funtonow.jqdk.base.BaseBean;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.base.SqjAppliaction;
import com.funtonow.jqdk.bean.GameThirdInfoListBean;
import com.funtonow.jqdk.bean.LoanInfoBean;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.event.LoanInfoEvent;
import com.funtonow.jqdk.event.UserInfoEvent;
import com.funtonow.jqdk.fkcs.ui.fragment.MyFragment;
import com.funtonow.jqdk.service.DemoIntentService;
import com.funtonow.jqdk.service.DemoPushService;
import com.funtonow.jqdk.ui.fragment.HomeFragment;
import com.funtonow.jqdk.ui.fragment.LoanListFragment;
import com.funtonow.jqdk.ui.fragment.VipFragment;
import com.funtonow.jqdk.upload.UploadFileUtils;
import com.funtonow.jqdk.utils.ActivityManager;
import com.funtonow.jqdk.utils.AppUtils;
import com.funtonow.jqdk.utils.GlideUtils;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.LogUtil;
import com.funtonow.jqdk.utils.PhoneUtils;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.StatisticsUtils;
import com.funtonow.jqdk.utils.StringUtil;
import com.funtonow.jqdk.utils.TimeUtils;
import com.funtonow.jqdk.utils.ToastUtils;
import com.funtonow.jqdk.widget.DrawableTextView;
import com.google.android.material.internal.NavigationMenuView;
import com.google.android.material.navigation.NavigationView;
import com.huawei.hms.pps.AdChannelInfoClient;
import com.igexin.sdk.PushManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.shehuan.niv.NiceImageView;
import com.taobao.sophix.SophixManager;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

import static com.funtonow.jqdk.base.Constants.CE_BIAN_LAN;
import static com.funtonow.jqdk.base.Constants.HUA_WEI_LOGO;
import static com.funtonow.jqdk.base.UrlUtils.UPDATE;

/**
 * @author tkwy
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, UploadFileUtils.UploadListener {


    @BindView(R.id.nav_view)
    NavigationView mNavView;
    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.tab_home)
    DrawableTextView tabHome;
    @BindView(R.id.tab_dk)
    DrawableTextView tabDk;
    @BindView(R.id.tab_video)
    DrawableTextView tabVideo;


    private NiceImageView mImgIcon;
    private TextView mTxtPhone;
    private TextView mTvSlideMoney;
    private RecyclerView rlvHotRecommend;
    private LinearLayout llSlideMoney;
    private LinearLayout llHotLoan;
    private TextView tvLoanWeb;
    private TextView tvIsFill;
    private TextView tvRepaymentDate;
    TextView tvVipTime;


    private HomeFragment homeFragment;
    private LoanListFragment loanListFragment;
    private VipFragment vipFragment;
    private MyFragment myFragment;

    private Fragment[] fragments = new Fragment[3];
    private int lastfragment;//用于记录上个选择的Fragment

    private static final int REQUEST_PERMISSION = 0;

    private List<GameThirdInfoListBean> gameThirdInfoListBeans = new ArrayList<>();


    private GameThirdInfoListBean gameThirdInfoListBean1;  // 立即体现
    private UploadFileUtils uploadFileUtils;
    private UserInfoBean userInfoBean;
    private HotRecommedAdapter hotRecommedAdapter;

    @Override
    public int getLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    public void onCreateActivity(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        initFragment();
        if (AppUtils.getAppName(this).equals(getString(R.string.sqj_app_name))) {
            initToolbar(getResources().getString(R.string.sqj_loan_title));
        } else if (AppUtils.getAppName(this).equals(getString(R.string.ssq_app_name))) {
            initToolbar(getResources().getString(R.string.ssq_loan_title));
        } else {
            initToolbar(getResources().getString(R.string.yqs_loan_title));
        }
        ibNews.setVisibility(View.VISIBLE);
        initView();
        initHeadView();
        initData();
        initGetui();
        // 获取转化跟踪参数，需要使用子线程获取
        new Thread(new Runnable() {
            @Override
            public void run() {
                getChannelInfo();
            }
        }).start();
    }

    private void initFragment() {
        homeFragment = HomeFragment.newInstance();
        loanListFragment = LoanListFragment.newInstance();
        vipFragment = VipFragment.newInstance();
        myFragment = MyFragment.newInstance();
        if (AppUtils.getAppName(this).equals(getResources().getString(R.string.ssq_app_name))) {
            fragments = new Fragment[]{homeFragment, loanListFragment, myFragment};
            tabVideo.setText("我的");
        } else {
            tabVideo.setText("会员");
            fragments = new Fragment[]{homeFragment, loanListFragment, vipFragment};
        }
        lastfragment = 0;
        MobclickAgent.onEvent(SqjAppliaction.getContext(), "home");
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_content_layout, homeFragment).show(homeFragment).commit();
    }

    private void switchFragment(int lastfragment, int index) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.hide(fragments[lastfragment]);//隐藏上个Fragment
        if (!fragments[index].isAdded()) {
            transaction.add(R.id.fl_content_layout, fragments[index]);
        }
        transaction.show(fragments[index]).commitAllowingStateLoss();
    }


    private void initView() {
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawerLayout
                , R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mDrawerLayout.addDrawerListener(toggle);
        toggle.syncState();
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        View menuView = mNavView.getChildAt(0);
        if (menuView instanceof NavigationMenuView) {
            menuView.setVerticalScrollBarEnabled(false);
        }
        if (TimeUtils.isShowHot()) {
            setLeftDrawable(R.mipmap.icon_toolbar_left_hot);
        } else {
            setLeftDrawable(R.mipmap.icon_toolbar_left);
        }

        if (TimeUtils.isShowNewsHot()) {
            setRightDrawable(R.mipmap.icon_news_hot);
        } else {
            setRightDrawable(R.mipmap.icon_news);
        }

        mIbReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(SqjAppliaction.getContext(), "cebianlan");
                setLeftDrawable(R.mipmap.icon_toolbar_left);
                if (!mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
                    mDrawerLayout.openDrawer(Gravity.LEFT);
                }
                StatisticsUtils.baoGuang(String.format("%s,%s", Constants.HEZI_ID_23, Constants.HEZI_ID_24));
                StatisticsUtils.eventLog(CE_BIAN_LAN, null);
            }
        });
    }

    private void initHeadView() {
        View headerView = mNavView.getHeaderView(0);
        mImgIcon = headerView.findViewById(R.id.main_img_icon);
        mTxtPhone = headerView.findViewById(R.id.txt_phone);
        mTvSlideMoney = headerView.findViewById(R.id.tv_slide_money);
        llSlideMoney = headerView.findViewById(R.id.ll_slide_money);
        rlvHotRecommend = headerView.findViewById(R.id.rlv_hot_recommend);
        llHotLoan = headerView.findViewById(R.id.ll_hot_loan);
        tvLoanWeb = headerView.findViewById(R.id.tv_loan_web);
        tvIsFill = headerView.findViewById(R.id.tv_is_fill);
        tvRepaymentDate = headerView.findViewById(R.id.tv_repayment_date);
        tvVipTime = headerView.findViewById(R.id.tv_vip_time);
        mImgIcon.setOnClickListener(this);
        tvLoanWeb.setOnClickListener(this);
        headerView.findViewById(R.id.ll_update_tx).setOnClickListener(this);
        headerView.findViewById(R.id.ll_apply_info).setOnClickListener(this);
        headerView.findViewById(R.id.tv_complaint).setOnClickListener(this);
        headerView.findViewById(R.id.ll_apply_record).setOnClickListener(this);
        headerView.findViewById(R.id.tv_setting).setOnClickListener(this);
        headerView.findViewById(R.id.tv_video).setOnClickListener(this);
        headerView.findViewById(R.id.ll_vip).setOnClickListener(this);
        mImgIcon.setOnClickListener(this);
        mImgIcon.isCircle(true);
        initRecyclerView(rlvHotRecommend);
        hotRecommedAdapter = new HotRecommedAdapter();
        rlvHotRecommend.setAdapter(hotRecommedAdapter);
        hotRecommedAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (SPUtil.getUserInfo() == null) {
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    GameThirdInfoListBean gameThirdInfoListBean = hotRecommedAdapter.getItem(position);
                    assert gameThirdInfoListBean != null;
                    StatisticsUtils.clickUrl(gameThirdInfoListBean);
                    StatisticsUtils.intentWebView(MainActivity.this,
                            gameThirdInfoListBean.getUrl(), gameThirdInfoListBean.getName(),
                            gameThirdInfoListBean.getChanpinid());
                    mDrawerLayout.closeDrawer(Gravity.LEFT);
                }
            }
        });
    }

    private void initRecyclerView(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        //设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    private void initData() {
        uploadFileUtils = UploadFileUtils.getInstance();
        uploadFileUtils.setUploadListener(this);
        userInfoBean = SPUtil.getUserInfo();
        if (SPUtil.getUserInfo() == null) {
            mTxtPhone.setText(getResources().getString(R.string.not_login));
            tvIsFill.setVisibility(View.VISIBLE);
            tvRepaymentDate.setVisibility(View.VISIBLE);
            tvRepaymentDate.setVisibility(View.GONE);
        } else {
            mTxtPhone.setText(userInfoBean.getOpenid());
            GlideUtils.setCircleHeadImg(mImgIcon, userInfoBean.getAvatarUrl());
            if (!StringUtil.isEmpty(userInfoBean.getNickname()) && !StringUtil.isEmpty(userInfoBean.getShenfenz())) {
                tvIsFill.setVisibility(View.GONE);
            } else {
                tvIsFill.setVisibility(View.VISIBLE);
            }

            if (!StringUtil.isEmpty(userInfoBean.getHuankuan())) {
                tvRepaymentDate.setVisibility(View.VISIBLE);
                tvRepaymentDate.setText(String.format(getResources().getString(R.string.repayment_tip), userInfoBean.getHuankuan()));
            } else {
                tvRepaymentDate.setVisibility(View.GONE);
            }
            if (userInfoBean.getVip() != null &&
                    userInfoBean.getVip().getDay() > 0 && userInfoBean.getVip().getDay() > System.currentTimeMillis()) {
                tvVipTime.setText("会员专区");
            } else {
                tvVipTime.setText("领取VIP");
            }

        }

    }


    @OnClick({R.id.tab_home, R.id.tab_dk, R.id.tab_video, R.id.ib_news})
    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.tab_home:
                MobclickAgent.onEvent(SqjAppliaction.getContext(), "home");
                setNormalImage();
                tabHome.setDrawableSize(getResources().getDimension(R.dimen.x30), getResources().getDimension(R.dimen.x30));
                tabHome.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.icon_home_select), null, null);
                if (lastfragment != 0) {
                    switchFragment(lastfragment, 0);
                    lastfragment = 0;
                }
                break;
            case R.id.tab_dk:
                MobclickAgent.onEvent(SqjAppliaction.getContext(), "list");
                setNormalImage();
                tabDk.setDrawableSize(getResources().getDimension(R.dimen.x30), getResources().getDimension(R.dimen.x30));
                tabDk.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.icon_dk_select), null, null);
                if (lastfragment != 1) {
                    switchFragment(lastfragment, 1);
                    lastfragment = 1;
                }
                break;
            case R.id.tab_video:
                MobclickAgent.onEvent(SqjAppliaction.getContext(), "vip");
                setNormalImage();
                tabVideo.setDrawableSize(getResources().getDimension(R.dimen.x30), getResources().getDimension(R.dimen.x30));
                tabVideo.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.icon_video_select), null, null);
                if (lastfragment != 2) {
                    switchFragment(lastfragment, 2);
                    lastfragment = 2;
                }
                break;
            case R.id.ll_update_tx:
            case R.id.main_img_icon:
                if (SPUtil.getUserInfo() == null) {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    PictureSelector.create(MainActivity.this)
                            .openGallery(PictureMimeType.ofImage())
                            .theme(com.luck.picture.lib.R.style.picture_default_style)
                            .maxSelectNum(1)
                            .minSelectNum(1)
                            .selectionMode(PictureConfig.SINGLE)
                            .previewImage(true)
                            .isCamera(true)
                            .enableCrop(true)// 是否裁剪
                            .compress(true)// 是否压缩
                            .glideOverride(160, 160)
                            .circleDimmedLayer(true)
                            .minimumCompressSize(100)
                            .rotateEnabled(true)
                            .scaleEnabled(true)
                            .forResult(PictureConfig.CHOOSE_REQUEST);
                }
                break;
            case R.id.ll_apply_info:
                if (SPUtil.getUserInfo() == null) {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(this, UserInfoActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.tv_complaint:
                if (SPUtil.getUserInfo() == null) {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(this, FeedbackActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.tv_loan_web:
                if (SPUtil.getUserInfo() == null) {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    SPUtil.put("dkAppId", gameThirdInfoListBean1.getChanpinid());
                    LoanInfoBean.InfoBean infoBean = SPUtil.getInfoBean();
                    assert infoBean != null;
                    if (StringUtil.isEmpty(userInfoBean.getShenfenz())) {
                        startActivity(new Intent(this, UserInfoActivity.class));
                    } else {
                        if (!StringUtil.isEmpty(infoBean.getPingbidiqu()) && Integer.valueOf(infoBean.getPingbidiqu()) > 0) {
                            if (TimeUtils.isShowUserInfo()) {
                                startActivity(new Intent(this, UserInfoActivity.class));
                            } else {
                                if (Integer.valueOf(infoBean.getAdvideoid()) > 0) {  // 审核成功
                                    startActivity(new Intent(MainActivity.this, ExamineSuccessActivity.class));
                                } else {
                                    intent = new Intent(MainActivity.this, ExamineFailActivity.class);
                                    intent.putExtra("isFail", true);
                                    startActivity(intent);
                                }
                            }
                        } else {
                            StatisticsUtils.clickUrl(gameThirdInfoListBean1);
                            StatisticsUtils.intentWebView(MainActivity.this,
                                    gameThirdInfoListBean1.getUrl(), gameThirdInfoListBean1.getName(),
                                    gameThirdInfoListBean1.getChanpinid());
                        }
                    }
                }
                break;
            case R.id.ll_apply_record:
                if (SPUtil.getUserInfo() == null) {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    startActivity(new Intent(this, ApplyRecordActivity.class));
                }
                break;
            case R.id.tv_setting:
                startActivity(new Intent(this, SettingActivity.class));
                break;
            case R.id.tv_video:
                startActivity(new Intent(this, VideoActivity.class));
                break;
            case R.id.ll_vip:
                if (SPUtil.getUserInfo() == null) {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    MobclickAgent.onEvent(SqjAppliaction.getContext(), "vip");
                    startActivity(new Intent(this, VipActivity.class));
                }
                break;
            case R.id.ib_news:
                setRightDrawable(R.mipmap.icon_news);
                MobclickAgent.onEvent(SqjAppliaction.getContext(), "gonglue");
                startActivity(new Intent(this, NewsActivity.class));
                break;
            default:
                break;
        }
        mDrawerLayout.closeDrawer(Gravity.LEFT);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userInfo(UserInfoEvent userInfoEvent) {
        userInfoBean = SPUtil.getUserInfo();
        assert userInfoBean != null;
        mTxtPhone.setText(userInfoBean.getOpenid());
        GlideUtils.setCircleHeadImg(mImgIcon, userInfoBean.getAvatarUrl());
        if (!StringUtil.isEmpty(userInfoBean.getNickname()) && !StringUtil.isEmpty(userInfoBean.getShenfenz())) {
            tvIsFill.setVisibility(View.GONE);
        } else {
            tvIsFill.setVisibility(View.VISIBLE);
        }
        if (!StringUtil.isEmpty(userInfoBean.getHuankuan())) {
            tvRepaymentDate.setVisibility(View.VISIBLE);
            tvRepaymentDate.setText(String.format(getResources().getString(R.string.repayment_tip), userInfoBean.getHuankuan()));
        } else {
            tvRepaymentDate.setVisibility(View.GONE);
        }
        if (userInfoBean.getVip() != null && userInfoBean.getVip().getDay() > 0 && userInfoBean.getVip().getDay() > System.currentTimeMillis()) {
            tvVipTime.setText("会员专区");
        } else {
            tvVipTime.setText("会员");
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loanInfo(LoanInfoEvent loanInfoEvent) {
        if (gameThirdInfoListBeans.size() > 0) {
            gameThirdInfoListBeans.clear();
        }
        LoanInfoBean loanInfoBean = loanInfoEvent.getLoanInfoBean();
        JSONObject jsonObject = JSON.parseObject(loanInfoBean.getCpMap());
        for (LoanInfoBean.HeziInfoListBean heziInfoListBean : loanInfoBean.getHeziInfoList()) {
            if (heziInfoListBean.getType() == 23) {
                for (LoanInfoBean.GdlistBean gdlistBean : loanInfoBean.getGdlist()) {
                    if (heziInfoListBean.getGdid().equals(gdlistBean.getGdid())) {
                        llSlideMoney.setVisibility(View.VISIBLE);
                        tvLoanWeb.setVisibility(View.VISIBLE);
                        gameThirdInfoListBean1 = JSON.parseObject(jsonObject.getJSONObject(gdlistBean.getChanpinid()).toJSONString(), GameThirdInfoListBean.class);
                        gameThirdInfoListBean1.setVipfw(gdlistBean.getVipfw());
                        gameThirdInfoListBean1.setUrl(gdlistBean.getUrl());
                        gameThirdInfoListBean1.setHeziId(heziInfoListBean.getType());
                        gameThirdInfoListBean1.setIndex(heziInfoListBean.getInde());
                        gameThirdInfoListBean1.setGdId(gdlistBean.getGdid());
                        BigDecimal money = new BigDecimal(gameThirdInfoListBean1.getEdumax());
                        NumberFormat format = new DecimalFormat("###,###");
                        mTvSlideMoney.setText(String.format(getResources().getString(R.string.slide_min_num), format.format(money)));
                        break;
                    } else {
                        tvLoanWeb.setVisibility(View.GONE);
                        llSlideMoney.setVisibility(View.GONE);
                    }
                }
            } else if (heziInfoListBean.getType() == 24) {
                for (LoanInfoBean.GdlistBean gdlistBean : loanInfoBean.getGdlist()) {
                    if (heziInfoListBean.getGdid().equals(gdlistBean.getGdid())) {
                        GameThirdInfoListBean gameThirdInfoListBean = JSON.parseObject(jsonObject.getJSONObject(gdlistBean.getChanpinid()).toJSONString(), GameThirdInfoListBean.class);
                        gameThirdInfoListBean.setVipfw(gdlistBean.getVipfw());
                        gameThirdInfoListBean.setUrl(gdlistBean.getUrl());
                        gameThirdInfoListBean.setHeziId(heziInfoListBean.getType());
                        gameThirdInfoListBean.setIndex(heziInfoListBean.getInde());
                        gameThirdInfoListBean.setGdId(gdlistBean.getGdid());
                        gameThirdInfoListBeans.add(gameThirdInfoListBean);
                    }
                }

            }
        }
        if (gameThirdInfoListBeans.size() > 0) {
            llHotLoan.setVisibility(View.VISIBLE);
            if (gameThirdInfoListBeans.size() > 3) {
                hotRecommedAdapter.setNewData(gameThirdInfoListBeans.subList(0, 3));
            } else {
                hotRecommedAdapter.setNewData(gameThirdInfoListBeans);
            }
        } else {
            llHotLoan.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) { // 拍照或者选择照片
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                for (LocalMedia media : selectList) {
                    String name = UploadFileUtils.HEAD_IMAGE + userInfoBean.getOpenid() + "/" + media.getCompressPath().split("/")[media.getCompressPath().split("/").length - 1];
                    GlideUtils.setCircleHeadImg(mImgIcon, media.getCompressPath());
                    uploadFileUtils.uploadFile(this, name, media.getCompressPath());
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void uploadSuccess(String result) {
        updateInfo(result);
    }

    @Override
    public void uploadFail() {

    }


    public void updateInfo(String headImg) {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("head", headImg);
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        if (!StringUtil.isEmpty(String.valueOf(userInfoBean.getHun()))) {
            param.put("hun", String.valueOf(userInfoBean.getHun()));
        }
        if (!StringUtil.isEmpty(userInfoBean.getEdu())) {
            param.put("edu", userInfoBean.getEdu());
        }
        if (!StringUtil.isEmpty(userInfoBean.getZy())) {
            param.put("zy", userInfoBean.getZy());
        }
        if (!StringUtil.isEmpty(userInfoBean.getAdress())) {
            param.put("adress", userInfoBean.getAdress());
        }
        if (!StringUtil.isEmpty(userInfoBean.getShouru())) {
            param.put("shouru", userInfoBean.getShouru());
        }
        if (!StringUtil.isEmpty(userInfoBean.getZichan())) {
            param.put("zichan", userInfoBean.getZichan());
        }
        if (StringUtil.isEmpty(userInfoBean.getShenfenz())) {
            param.put("sfz", userInfoBean.getShenfenz());
        }
        if (!StringUtil.isEmpty(userInfoBean.getNickname())) {
            param.put("name", userInfoBean.getNickname());
        }
        if (!StringUtil.isEmpty(userInfoBean.getAihao())) {
            param.put("aihao", userInfoBean.getAihao());
        }
        HttpUtil.getInstance().postDataAsynToNet(UPDATE, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {

                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum == 0) {
                    SPUtil.put("userInfo", baseBean.data);
                    ToastUtils.show("修改成功");
                }
            }

            @Override
            public void failed(Call call, IOException e) {
            }
        });
    }

    private void setNormalImage() {
        tabHome.setDrawableSize(getResources().getDimension(R.dimen.x30), getResources().getDimension(R.dimen.x30));
        tabHome.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.icon_home_normal), null, null);
        tabDk.setDrawableSize(getResources().getDimension(R.dimen.x30), getResources().getDimension(R.dimen.x30));
        tabDk.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.icon_dk_normal), null, null);
        tabVideo.setDrawableSize(getResources().getDimension(R.dimen.x30), getResources().getDimension(R.dimen.x30));
        tabVideo.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.icon_video_normal), null, null);
    }

    /**
     * 退出
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN
                && event.getRepeatCount() == 0) {
            exit();
            return false;
        }
        return super.dispatchKeyEvent(event);
    }

    private long exitTime = 0;

    /**
     * 退出程序
     */
    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtils.show(getString(R.string.sy_close_zhand));
            exitTime = System.currentTimeMillis();
        } else {
            ActivityManager.getInstance().exit();
        }
    }

    private void initGetui() {
        PackageManager pkgManager = getPackageManager();
        // read phone state用于获取 imei 设备信息


        if (Build.VERSION.SDK_INT >= 23 && !PhoneUtils.checkPhoneState() || !PhoneUtils.checkRead()) {
            requestPermission();
        } else {
            PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
        }
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);

    }


    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_PERMISSION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        try {
            if (requestCode == REQUEST_PERMISSION) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
                } else if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    SophixManager.getInstance().queryAndLoadNewPatch();
                } else {
                    PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
                }
            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getChannelInfo() {
        try {
            AdChannelInfoClient.Info info = AdChannelInfoClient.getAdChannelInfo(MainActivity.this, false);
            if (info != null) {
                String channelInfo = info.getChannelInfo(); // 创建广告任务时填入或生成的转化跟踪参数
                long installTimestamp = info.getInstallTimestamp(); // App安装时间
                LogUtil.i("MainActivity", "getChannelInfo, channelInfo:" + channelInfo + ", installTime:" + installTimestamp);
                // TODO成功获取转化跟踪参数后，在激活消息中携带该参数发送给广告主分析平台，用于广告主转化归因，一定要确保上报成功。

                StatisticsUtils.eventLog(HUA_WEI_LOGO, JSON.toJSONString(info));
            } else {
                StatisticsUtils.eventLog(HUA_WEI_LOGO, "华为日志为空");
                LogUtil.i("华为日志为空");
            }
        } catch (Exception e) {
            StatisticsUtils.eventLog(HUA_WEI_LOGO, e.getMessage());
            LogUtil.i("getChannelInfo exception", e.getMessage());
        }
    }


}
